//
//  MMGWelcomeController.swift
//  MyMicroblog
//
//  Created by Mac on 17/1/6.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let bottomMargin: CGFloat = 120
private let imgWidth: CGFloat = 85
class MMGWelcomeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 执行动画
        addAnimation()
    }

    // 搭建 UI 界面
    private func setupUI() {
        
        view.backgroundColor = UIColor.white
        
        // 将图像和欢迎 label 加载到子视图中
        self.view.addSubview(iconView)
        self.view.addSubview(welcomeLabel)
        
        // 设置约束
        iconView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(-bottomMargin)
            make.size.equalTo(CGSize(width: imgWidth, height: imgWidth))
        }
        
        welcomeLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(iconView)
            make.top.equalTo(iconView.snp.bottom).offset(20)
        }
        
        // 设置文字隐藏
        welcomeLabel.alpha = 0
        
        // 为图片设置圆角
        iconView.layer.cornerRadius = imgWidth * 0.5
        iconView.layer.masksToBounds = iconView.layer.cornerRadius > 0
        
        // 获取网络图片
        iconView.sd_setImage(with: MMGUserAccountViewModel.shared.headURL)
    }
    
    // 添加动画效果
    private func addAnimation() {
        // 计算图片移动距离
        let offsetY = -(UIScreen.main.bounds.height - bottomMargin - iconView.bounds.height)
        
        self.iconView.snp.updateConstraints({ (make) in
            make.bottom.equalTo(self.view).offset(offsetY)
        })
        
        // 开始动画
        UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options:[], animations: {
            
            self.view.layoutIfNeeded()
        }, completion: { (finished) in
            //动画效果完成的回调
            UIView.animate(withDuration: 1, animations: {
                self.welcomeLabel.alpha = 1
            }, completion: { (_) -> () in
                
                //UIApplication.shared.keyWindow?.rootViewController = HMTabBarController()
                NotificationCenter.default.post(name: NSNotification.Name(kChoseRootViewController), object: nil)
            })
        })
    }
    
    // 懒加载图像
    private lazy var iconView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "avatar_default_big"))
    
    // 懒加载欢迎 label
    lazy var welcomeLabel:UILabel = UILabel(text: "欢迎回来", textColor: UIColor.darkGray, textFontSize: 16)

}
